package team.first.movieapiv3.controller;

import cn.hutool.core.convert.Convert;
import io.swagger.annotations.ApiOperation;
import org.neo4j.ogm.cypher.BooleanOperator;
import org.neo4j.ogm.cypher.ComparisonOperator;
import org.neo4j.ogm.cypher.Filter;
import org.neo4j.ogm.cypher.Filters;
import org.neo4j.ogm.cypher.query.Pagination;
import org.neo4j.ogm.cypher.query.SortOrder;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv3.dto.RequestStaff;
import team.first.movieapiv3.staff.StaffNode;
import team.first.movieapiv3.util.SessionFactoryUtil;
import team.first.movieapiv3.vo.ApiResponse;
import team.first.movieapiv3.vo.ApiResponsePaging;

import java.util.Collection;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv3.controller
 * @Date: 2021/12/22 9:14
 * @Description:
 */
@RestController
public class StaffController {
    static SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory("team.first.movieapiv3.staff");

    /**
     * 1.4 获取指定编号的演员信息
     * 接口地址：GET /api/v3/staff/{staffId}
     */
    @ApiOperation("1.4 GET: 获取指定编号的影人信息")
    @GetMapping("/api/v3/staff/{staffId}")
    public ApiResponse<StaffNode> getStaffById(@PathVariable("staffId") Integer staffId) {
        ApiResponse<StaffNode> apiResponse = new ApiResponse<>();
        try {
            Session session = sessionFactory.openSession();
            StaffNode staffNode = session.load(StaffNode.class, staffId);
            apiResponse.setCode(200).setSuccess(true).setMessage("请求成功").setData(staffNode);
        } catch (Exception e) {
            apiResponse.setCode(500).setSuccess(false).setMessage("请求失败");
        }

        return apiResponse;
    }

    /**
     * 2.5根据条件分页获取的影人信息
     * 接口地址:POST /api/v3/staffs
     */
    @PostMapping("/api/v3/staffs")
    @ApiOperation("1.5 POST： 根据条件分页获取的影人信息")
    public ApiResponsePaging<Collection<StaffNode>> getStuff(RequestStaff requestStaff) {
        ApiResponsePaging<Collection<StaffNode>> responsePaging = new ApiResponsePaging<>();

        try {
            Session session = sessionFactory.openSession();

            Filters filters = new Filters();

            // 建立查询条件
            if (requestStaff.getChineseName() != null) {
                //  加上"*"为模糊匹配，neo4j全栈开发，124页
                filters.add(new Filter("chineseName", ComparisonOperator.LIKE, "*" + requestStaff.getChineseName() + "*"));
            }

            if (requestStaff.getEnglishName() != null) {
                // 用于将此筛选器附加到上一个筛选器的布尔运算符。
                // 如果筛选器不是列表中的第一个也是唯一一个筛选器，则BooleanOperator为必填项。
                Filter filter = new Filter("englishName", ComparisonOperator.LIKE, "*" + requestStaff.getEnglishName() + '*');
                filter.setBooleanOperator(BooleanOperator.AND);
                filters.add(filter);
            }

            if (requestStaff.getGender() != null) {
                Filter filter = new Filter("gender", ComparisonOperator.LIKE, "*" + requestStaff.getGender() + "*");
                filter.setBooleanOperator(BooleanOperator.AND);
                filters.add(filter);
            }

            if (requestStaff.getRegion() != null) {
                Filter filter = new Filter("region", ComparisonOperator.LIKE, "*" + requestStaff.getRegion() + "*");
                filter.setBooleanOperator(BooleanOperator.AND);
                filters.add(filter);
            }

            Collection<StaffNode> staffNodeCollection = null;

            /**
             * 分页查询，页数从0开始
             * public Pagination(int pageNumber, int pageSize) {
             *
             *     if (pageNumber < 0) {
             *         throw new RuntimeException("Page number must not be negative");
             *     }
             *
             *     if (pageSize < 1) {
             *         throw new RuntimeException("Page size must greater than zero");
             *     }
             *
             *     this.index = pageNumber;
             *     this.size = pageSize;
             * }
             */
            Pagination pagination = null;
            if (requestStaff.getPageNumber() != null) {
                pagination = new Pagination(requestStaff.getPageNumber() - 1, requestStaff.getPagerSize());
                responsePaging.setPageNumber(requestStaff.getPageNumber());
                responsePaging.setPageSize(requestStaff.getPagerSize());
            }

            // 排序
            if (requestStaff.getOrderField() != null) {
                // 根据排序规则排序，默认升序
                if (requestStaff.getOrderDirection() != null && "DESC".equalsIgnoreCase(requestStaff.getOrderDirection())) {
                    staffNodeCollection = session.loadAll(StaffNode.class, filters, new SortOrder(SortOrder.Direction.DESC, requestStaff.getOrderField()), pagination);
                } else {
                    staffNodeCollection = session.loadAll(StaffNode.class, filters, new SortOrder(SortOrder.Direction.ASC, requestStaff.getOrderField()), pagination);
                }
            } else {
                staffNodeCollection = session.loadAll(StaffNode.class, filters, pagination);
            }
            responsePaging.setCode(200).setSuccess(true).setMessage("请求成功").setData(staffNodeCollection).setTotalRow(Convert.toInt(session.count(StaffNode.class, filters)));
        } catch (Exception e) {
            e.printStackTrace();
            responsePaging.setCode(500).setSuccess(false).setMessage("请求失败");
        }
        return responsePaging;
    }
}
